<?php

namespace App\Http\Controllers\Admin\Logs;

use App\Http\Controllers\AdminController;
use App\Models\Logs\AccessLog;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;

class AccessLogController extends AdminController
{

    public function data(Request $request)
    {
        $model = AccessLog::query()->select(['id', 'path', 'method', 'ip', 'ip_address', 'platform', 'browser', 'created_at']);
        if ($keyword = $request->get('keywords')) {
            $model->where('path', 'like', filterStr($keyword).'%');
        }
        if ($method = $request->get('method')) {
            $model->where('method', $method);
        }
        if ($ip = $request->get('ip')) {
            $model->where('ip', 'like', $ip.'%');
        }
        $list = $model->orderByDesc('id')->paginate($request->get('limit', 10));
        return $this->succeed([
            'total' => $list->total(),
            'rows'  => $list->items()
        ]);
    }

    public function show($id)
    {
        $item = AccessLog::query()->findOrFail($id, ['input', 'platform', 'browser', 'header']);
        $item["input"] = json_decode($item["input"], true);
        $item['header'] = json_decode($item['header'], true);
        if (!empty($item['header']['user-agent'])) {
            $agent = new Agent();
            $agent->setUserAgent($item['header']['user-agent'][0]);
            $item["platform_version"] = $agent->version($item['platform']);
            $item["browser_version"] = $agent->version($item['browser']);
        }
        return $this->succeed($item);
    }
}
